// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space 
// Source File Name:   ATHandler.java

package cn.sendsms;

import java.io.IOException;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;

// Referenced classes of package cn.sendsms:
//			AATHandler, GatewayException, TimeoutException, ModemGateway, 
//			ModemDriver, MessageProtocols, MessageClasses, AsyncEvents

class ATHandler extends AATHandler
{

	protected ModemDriver modemDriver;

	public ATHandler(ModemGateway gateway)
	{
		super(gateway);
		modemDriver = gateway.getModemDriver();
		terminators = new String[12];
		terminators[0] = "OK\\s";
		terminators[1] = "\\s*[\\p{ASCII}]*\\s+OK\\s";
		terminators[2] = "ERROR\\s";
		terminators[3] = "ERROR:\\s*\\d+\\s";
		terminators[4] = "\\+CM[ES]\\s+ERROR:\\s*\\d+\\s";
		terminators[5] = "\\+CPIN:\\s*READY\\s";
		terminators[6] = "\\+CPIN:\\s*SIM\\s*BUSY\\s";
		terminators[7] = "\\+CPIN:\\s*SIM\\s*PIN\\s";
		terminators[8] = "\\+CMTI:\\s*\\p{Punct}[\\p{ASCII}]+\\p{Punct}\\p{Punct}\\s*\\d+\\s";
		terminators[9] = "\\+CDSI:\\s*\\p{Punct}[\\p{ASCII}]+\\p{Punct}\\p{Punct}\\s*\\d+\\s";
		terminators[10] = "RING\\s";
		terminators[11] = "\\+CLIP:\\s*\\p{Punct}[\\p{ASCII}]+\\p{Punct}\\p{Punct}\\s*\\d+\\s";
	}

	void sync()
		throws IOException, InterruptedException
	{
		modemDriver.write("ATZ\r");
		Thread.sleep(200L);
	}

	void reset()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
	}

	void echoOff()
		throws IOException, InterruptedException
	{
		modemDriver.write("ATE0\r");
		Thread.sleep(200L);
		modemDriver.clearBuffer();
	}

	void init()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CLIP=1\r");
		modemDriver.getResponse();
		modemDriver.write("AT+COPS=0\r");
		modemDriver.getResponse();
	}

	boolean isAlive()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT\r");
		modemDriver.getResponse();
		return modemDriver.isOk();
	}

	String getSimStatus()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CPIN?\r");
		return modemDriver.getResponse();
	}

	boolean enterPin(String pin)
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CPIN=\"_1_\"\r".replaceAll("_1_", pin));
		modemDriver.getResponse();
		return modemDriver.isOk();
	}

	boolean setVerboseErrors()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CMEE=1\r");
		modemDriver.getResponse();
		return modemDriver.isOk();
	}

	boolean setPduProtocol()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CMGF=0\r");
		modemDriver.getResponse();
		return modemDriver.isOk();
	}

	boolean setTextProtocol()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CMGF=1\r");
		modemDriver.getResponse();
		if (modemDriver.isOk())
		{
			modemDriver.write("AT+CSCS=\"HEX\"\r");
			modemDriver.getResponse();
			return modemDriver.isOk();
		} else
		{
			return false;
		}
	}

	boolean setIndications()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CNMI=2,1,0,2\r");
		modemDriver.getResponse();
		return modemDriver.isOk();
	}

	String getManufacturer()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CGMI\r");
		return modemDriver.getResponse();
	}

	String getModel()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CGMM\r");
		return modemDriver.getResponse();
	}

	String getSerialNo()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CGSN\r");
		return modemDriver.getResponse();
	}

	String getImsi()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CIMI\r");
		return modemDriver.getResponse();
	}

	String getSwVersion()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CGMR\r");
		return modemDriver.getResponse();
	}

	String getBatteryLevel()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CBC\r");
		return modemDriver.getResponse();
	}

	String getSignalLevel()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CSQ\r");
		return modemDriver.getResponse();
	}

	boolean setMemoryLocation(String mem)
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CPMS=\"" + mem + "\"\r");
		modemDriver.getResponse();
		return modemDriver.isOk();
	}

	void switchToCmdMode()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("+++");
		Thread.sleep(1000L);
	}

	boolean keepGsmLinkOpen()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CMMS=1\r");
		modemDriver.getResponse();
		return modemDriver.isOk();
	}

	int sendMessage(int size, String pdu, String phone, String text)
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		int refNo = -1;
		if (gateway.getProtocol() == MessageProtocols.PDU)
		{
			int errorRetries = 0;
			do
			{
				int responseRetries = 0;
				modemDriver.write("AT+CMGS=\"_1_\"\r".replaceAll("\"_1_\"", "" + size));
				Thread.sleep(100L);
				for (; !modemDriver.dataAvailable(); Thread.sleep(gateway.getDelayNoResponse()))
				{
					if (++responseRetries == gateway.getRetriesNoResponse())
						throw new GatewayException("Gateway is not responding, max number of retries reached.");
					gateway.getLogger().warn("ATHandler().SendMessage(): Still waiting for response (I) (" + responseRetries + ")...");
				}

				responseRetries = 0;
				modemDriver.clearBuffer();
				modemDriver.write(pdu);
				modemDriver.write('\032');
				String response;
				for (response = modemDriver.getResponse(); response.length() == 0; response = modemDriver.getResponse())
				{
					if (++responseRetries == gateway.getRetriesNoResponse())
						throw new GatewayException("Gateway is not responding, max number of retries reached.");
					gateway.getLogger().warn("ATHandler().SendMessage(): Still waiting for response (II) (" + responseRetries + ")...");
					Thread.sleep(gateway.getDelayNoResponse());
				}

				if (modemDriver.getLastError() == 0)
				{
					Matcher m = Pattern.compile("\\s*\\+CMGS: (\\d+)").matcher(response);
					if (m.find())
						refNo = Integer.parseInt(m.group(1));
					else
						refNo = -1;
					break;
				}
				if (modemDriver.getLastError() > 0)
				{
					if (++errorRetries == gateway.getRetriesCmsErrors())
					{
						gateway.getLogger().error(modemDriver.getLastErrorText() + ": Quit retrying, message lost...");
						refNo = -1;
						break;
					}
					gateway.getLogger().warn(modemDriver.getLastErrorText() + ": Retrying...");
					Thread.sleep(gateway.getDelayCmsErrors());
				} else
				{
					refNo = -1;
				}
			} while (true);
		} else
		if (gateway.getProtocol() == MessageProtocols.TEXT)
		{
			modemDriver.write("AT+CMGS=\"_1_\"\r".replaceAll("_1_", phone));
			modemDriver.clearBuffer();
			modemDriver.write(text);
			Thread.sleep(100L);
			modemDriver.write('\032');
			String response = modemDriver.getResponse();
			if (response.indexOf("OK\r") >= 0)
			{
				String tmp = "";
				int i;
				for (i = response.indexOf(":"); !Character.isDigit(response.charAt(i)); i++);
				for (; Character.isDigit(response.charAt(i)); i++)
					tmp = tmp + response.charAt(i);

				refNo = Integer.parseInt(tmp);
			} else
			{
				refNo = -1;
			}
		}
		return refNo;
	}

	String listMessages(MessageClasses messageClass)
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		if (gateway.getProtocol() == MessageProtocols.PDU)
		{
			if (messageClass == MessageClasses.ALL)
				modemDriver.write("AT+CMGL=4\r");
			else
			if (messageClass == MessageClasses.UNREAD)
				modemDriver.write("AT+CMGL=0\r");
			else
			if (messageClass == MessageClasses.READ)
				modemDriver.write("AT+CMGL=1\r");
		} else
		if (gateway.getProtocol() == MessageProtocols.TEXT)
			if (messageClass == MessageClasses.ALL)
				modemDriver.write("AT+CMGL=\"ALL\"\r");
			else
			if (messageClass == MessageClasses.UNREAD)
				modemDriver.write("AT+CMGL=\"REC UNREAD\"\r");
			else
			if (messageClass == MessageClasses.READ)
				modemDriver.write("AT+CMGL=\"REC READ\"\r");
		return modemDriver.getResponse();
	}

	boolean deleteMessage(int memIndex, String memLocation)
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		if (!setMemoryLocation(memLocation))
		{
			return false;
		} else
		{
			modemDriver.write("AT+CMGD=_1_\r".replaceAll("_1_", "" + memIndex));
			modemDriver.getResponse();
			return modemDriver.isOk();
		}
	}

	String getGprsStatus()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CGATT?\r");
		return modemDriver.getResponse();
	}

	String send(String s)
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write(s);
		return modemDriver.getResponse();
	}

	String getNetworkRegistration()
		throws GatewayException, TimeoutException, IOException
	{
		modemDriver.write("AT+CREG?\r");
		return modemDriver.getResponse();
	}

	void readStorageLocations()
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		modemDriver.write("AT+CPMS?\r");
		String response = modemDriver.getResponse();
		if (response.indexOf("+CPMS:") >= 0)
		{
			response = response.replaceAll("\\s*\\+CPMS:\\s*", "");
			for (StringTokenizer tokens = new StringTokenizer(response, ","); tokens.hasMoreTokens(); tokens.nextToken())
			{
				String loc = tokens.nextToken().replaceAll("\"", "");
				if (storageLocations.indexOf(loc) < 0)
					storageLocations += loc;
				tokens.nextToken();
			}

		}
	}

	AsyncEvents processUnsolicitedEvents(String response)
		throws IOException
	{
		AsyncEvents event = AsyncEvents.NOTHING;
		if (response.indexOf("+CMTI") >= 0)
			event = AsyncEvents.INBOUNDMESSAGE;
		else
		if (response.indexOf("+CDSI") >= 0)
			event = AsyncEvents.INBOUNDSTATUSREPORTMESSAGE;
		else
		if (response.indexOf("RING") >= 0)
		{
			try
			{
				switchToCmdMode();
			}
			catch (Exception e) { }
			gateway.getModemDriver().write("ATH\r");
			event = AsyncEvents.NOTHING;
		} else
		if (response.indexOf("+CLIP") >= 0)
			event = AsyncEvents.INBOUNDCALL;
		if (event != AsyncEvents.NOTHING)
			asyncEventResponse = response;
		return event;
	}

	String getAsyncEventResponse(AsyncEvents event)
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		String response = "";
		if (event == AsyncEvents.INBOUNDMESSAGE)
			response = asyncEventResponse;
		else
		if (event == AsyncEvents.INBOUNDSTATUSREPORTMESSAGE)
			response = asyncEventResponse;
		else
		if (event == AsyncEvents.INBOUNDCALL)
		{
			gateway.getLogger().debug("Inbound call detected!");
			response = asyncEventResponse;
			gateway.getModemDriver().getResponse();
		}
		return response;
	}
}
